<template>
  <div class="page-content" v-loading="loading">
    <div class="open-head-btn" @click="headShow = !headShow"></div>

    <el-row class="head" :style="{ height: headShow ? '38px' : 0 }">
      <el-input
        v-model="form.title"
        placeholder="请输入标题"
        style="max-width: 230px"
        @keyup.enter.native="search"
        ref="keyword"
      >
      </el-input>
      <el-button
        type="primary"
        style="margin-left: 0px"
        icon="el-icon-search"
        @click="search"
      >
        查询
      </el-button>
      <el-button
        type="primary"
        plain
        @click="addDialog('add', 0)"
        icon="el-icon-circle-plus"
        >发布新闻</el-button
      >
    </el-row>

    <div class="article-list">
      <div class="item" v-for="(item, index) in articleList" :key="index">
        <div class="left">
          <h1 class="title" @click="addDialog('edit', item.id)">
            {{ item.title }}
          </h1>
          <p class="des" v-html="item.des"></p>
          <div class="outer">
            <div>
              <el-button
                type="primary"
                icon="el-icon-edit"
                circle
                @click="addDialog('edit', item.id)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                @click="delnewsHandler(item.id)"
              ></el-button>
              <i class="iconfont" style="margin-left: 10px;">&#xe64c;</i>
              <span>{{ item.reading }}</span>
            </div>
            <!-- <div>
              <i class="iconfont">&#xe665;</i>
              <span>26</span>
            </div> -->
            <div>
              <i class="iconfont">&#xe65b;</i>
              <span>
                {{ item.writedate }}
              </span>
            </div>
          </div>
        </div>
        <div class="right">
          <div class="cover">
            <el-image
              :src="item.cover"
              :preview-src-list="[item.viewcover]"
              fit="none"
            ></el-image>
          </div>
        </div>
      </div>
    </div>
    <!-- 分页 -->
    <el-pagination
      background
      :page-size="pageSize"
      :total="total"
      :page-sizes="[10, 20, 30, 40, 50, 60, 70, 80]"
      :current-page.sync="page"
      @current-change="changePage"
      layout="total, prev, pager, next, jumper"
    />
    <el-dialog
      :title="newsform.title"
      :visible.sync="newsFormVisible"
      @opened="getediter"
      @close="clearediter"
      :close-on-click-modal="false"
      fullscreen
    >
      <el-form :model="newsform" :rules="rules" ref="newsform">
        <el-row :gutter="100">
          <el-col :xs="24" :sm="12" :lg="6">
            <form-input
              label="标题"
              v-model="newsform.newstitle"
              prop="newstitle"
              placeholder="请输入新闻标题"
              autocomplete="off"
            ></form-input>
          </el-col>
        </el-row>
        <el-row>
          <quill-editor
            class="editor"
            ref="quillEditor"
            v-model="newsform.content"
            :options="editorOption"
            @blur="onEditorBlur($event)"
            @focus="onEditorFocus($event)"
            @ready="onEditorReady($event)"
          />
          <el-upload
            class="upload-demo"
            :action="dataUrl"
            :before-upload="beforeUpload"
            :data="uploadData"
            :headers="headers"
            :on-success="upScuccess"
            ref="upload"
            multiple
            style="display:none"
          >
            <el-button
              type="primary"
              id="imgInput"
              v-loading.fullscreen.lock="fullscreenLoading"
              element-loading-text="插入中,请稍候"
            >
              点击上传
            </el-button>
          </el-upload>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="newsFormVisible = false" icon="el-icon-close"
          >取 消</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-check"
          v-if="isAddorEdit == '0'"
          @click="addnewsHandler"
          >{{ btnname }}</el-button
        >
        <el-button
          type="primary"
          icon="el-icon-check"
          v-else
          @click="UpdatenewsHandler(newsform.id)"
          >{{ btnname }}</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { GetNewsApi } from "@/api/cardApi";
import { GetNewsDetailApi } from "@/api/cardApi";
import { AddNewsApi } from "@/api/cardApi";
import { RemoveInewsApi } from "@/api/cardApi";
import { UpdateInewsApi } from "@/api/cardApi";
import moment from "moment";
import { quillEditor, Quill } from "vue-quill-editor";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import "@styles/quill.scss";
import { container, ImageExtend, QuillWatch } from "quill-image-extend-module";
import ImageResize from "quill-image-resize-module";
import { baseUrl } from "@/utils/config";

Quill.register("modules/ImageExtend", ImageExtend);
Quill.register("modules/ImageResize", ImageResize);
export default {
  inject: ["reload"],
  components: {
    quillEditor
  },
  data() {
    return {
      uploadData: {
        guestcode: "",
        gscode: ""
      },
      fullscreenLoading: false,
      headShow: true,
      loading: true,
      form: {
        title: "",
        cover: ""
      },
      page: 1,
      pageSize: 10,
      total: 0,
      articleList: [],
      newsFormVisible: false,
      btnname: "",
      isAddorEdit: "",
      headers: {
        Authorization: ""
      },
      newsform: {
        id: 0,
        title: "",
        newstitle: "",
        content: ""
      },
      dataUrl: baseUrl + "/api/Card/upload_Imgurl",
      editorOption: {
        modules: {
          ImageResize: {
            //调整大小组件。
            displayStyles: {
              backgroundColor: "black",
              border: "none",
              color: "white"
            },
            modules: ["Resize", "DisplaySize", "Toolbar"]
          },
          ImageExtend: {
            // 如果不作设置，即{}  则依然开启复制粘贴功能且以base64插入
            loading: true, // 可选参数 是否显示上传进度和提示语
            placeholder: "",
            name: "img", // 图片参数名
            size: 500, // 可选参数 图片大小，单位为M，1M = 1024kb
            methods: "POST", // 可选参数 图片上传方式  默认为post
            accept: "image/png, image/gif, image/jpeg, image/bmp, image/x-icon",
            action: this.dataUrl, // 服务器地址, 如果action为空，则采用base64插入图片
            // response 为一个函数用来获取服务器返回的具体图片地址
            // 例如服务器返回{code: 200; data:{ url: 'baidu.com'}}
            // 则 return res.data.url
            response: res => {
              let imgurl = "http://img.inheart.cn";
              return imgurl + res.statusText;
            },
            headers: xhr => {
              xhr.setRequestHeader("contentType", "application/json");
            }, // 可选参数 设置请求头部
            sizeError: () => {}, // 图片超过大小的回调
            start: () => {}, // 可选参数 自定义开始上传触发事件
            end: () => {}, // 可选参数 自定义上传结束触发的事件，无论成功或者失败
            error: () => {}, // 可选参数 上传失败触发的事件
            success: () => {}, // 可选参数  上传成功触发的事件
            change: (xhr, formData) => {} // 可选参数 每次选择图片触发，也可用来设置头部，但比headers多了一个参数，可设置formData
          },
          toolbar: {
            // 如果不上传图片到服务器，此处不必配置
            container: container, // container为工具栏，此次引入了全部工具栏，也可自行配置
            handlers: {
              image: function() {
                // 劫持原来的图片点击按钮事件
                QuillWatch.emit(this.quill.id);
              }
            }
          }
        }
      },
      rules: {
        newstitle: [{ required: true, message: "请输入标题", trigger: "blur" }]
      }
    };
  },
  mounted() {
    this.ArticleListData(1, "");
  },
  methods: {
    search() {
      this.ArticleListData(1, this.$refs.keyword.value);
    },
    ArticleListData(pageindex, keyword) {
      let userdata = JSON.stringify(this.$store.state.user.user.info);
      userdata = JSON.parse(userdata);
      let guestcode = userdata.reguserno;
      let gscode = userdata.gscode;
      let username = userdata.userName;
      let userid = userdata.id;
      let logintype = userdata.logintype;
      let posttype = userdata.posttype;
      GetNewsApi({
        guestcode: guestcode,
        gscode: gscode,
        pagesize: this.pageSize,
        pageindex: pageindex,
        keyword: keyword,
        username: username,
        userid: userid,
        menuename: "ArticleList",
        menucname: "新闻编辑",
        logintype: logintype,
        posttype: posttype,
        op_type: "查询"
      }).then(res => {
        this.loading = false;
        this.articleList = [];
        if (res.code == "0") {
          res.newsList.forEach(element => {
            element.writedate = moment(element.writedate).format(
              "YYYY-MM-DD hh:mm:ss"
            );
            if (element.src == "") {
              element.src =
                "http://www.iqp168.com/src/assets/img/noImg_Default.png";
            }
            this.articleList.push({
              id: element.id,
              title: element.title,
              des: element.body.replace(/<[^>]+>/g, ""),
              cover: element.src,
              viewcover: element.src + "&original=1",
              writedate: element.writedate,
              reading: element.reading
            });
          });
          this.total = res.datacount;
          this.dataUrl =
            this.dataUrl + "?guestcode=" + guestcode + "&gscode=" + gscode;
        } else {
          this.$message.error(res.msg);
        }
      });
    },
    changePage(val) {
      this.ArticleListData(val, this.$refs.keyword.value);
    },
    addDialog(type, val) {
      this.newsFormVisible = true;
      if (type == "add") {
        this.newsform.title = "发布新闻";
        this.btnname = "发 布";
        this.isAddorEdit = "0";
      }
      if (type == "edit") {
        this.btnname = "保 存";
        this.GetNewsDetailHandler(val);
        this.isAddorEdit = "1";
      }
    },
    addnewsHandler() {
      let userdata = JSON.stringify(this.$store.state.user.user.info);
      userdata = JSON.parse(userdata);
      let guestcode = userdata.reguserno;
      let gscode = userdata.gscode;
      let username = userdata.userName;
      let userid = userdata.id;
      let logintype = userdata.logintype;
      let posttype = userdata.posttype;
      AddNewsApi({
        guestcode: guestcode,
        gscode: gscode,
        query: this.newsform.newstitle,
        note: this.newsform.content,
        menuename: "ArticleList",
        menucname: "新闻编辑",
        username: username,
        userid: userid,
        logintype: logintype,
        posttype: posttype,
        op_type: "新增"
      }).then(res => {
        if (res.code == "0") {
          this.$message.success(res.msg);
          this.refresh();
        }
      });
    },
    delnewsHandler(val) {
      this.$confirm("您确定要删除吗", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let userdata = JSON.stringify(this.$store.state.user.user.info);
          userdata = JSON.parse(userdata);
          let guestcode = userdata.reguserno;
          let gscode = userdata.gscode;
          let username = userdata.userName;
          let userid = userdata.id;
          let logintype = userdata.logintype;
          let posttype = userdata.posttype;
          RemoveInewsApi({
            guestcode: guestcode,
            gscode: gscode,
            id: val,
            menuename: "ArticleList",
            menucname: "新闻编辑",
            username: username,
            userid: userid,
            logintype: logintype,
            posttype: posttype,
            op_type: "删除",
            note: val
          }).then(res => {
            if (res.code == "0") {
              this.$message.success(res.msg);
              this.refresh();
            }
          });
        })
        .catch(() => {});
    },
    UpdatenewsHandler(val) {
      let userdata = JSON.stringify(this.$store.state.user.user.info);
      userdata = JSON.parse(userdata);
      let guestcode = userdata.reguserno;
      let gscode = userdata.gscode;
      let username = userdata.userName;
      let userid = userdata.id;
      let logintype = userdata.logintype;
      let posttype = userdata.posttype;
      UpdateInewsApi({
        guestcode: guestcode,
        gscode: gscode,
        id: val,
        query: this.newsform.newstitle,
        note: this.newsform.content,
        menuename: "ArticleList",
        menucname: "新闻编辑",
        username: username,
        userid: userid,
        logintype: logintype,
        posttype: posttype,
        op_type: "更新"
      }).then(res => {
        if (res.code == "0") {
          this.$message.success(res.msg);
          this.refresh();
        }
      });
    },
    GetNewsDetailHandler(val) {
      let userdata = JSON.stringify(this.$store.state.user.user.info);
      userdata = JSON.parse(userdata);
      let guestcode = userdata.reguserno;
      let gscode = userdata.gscode;
      GetNewsDetailApi({
        guestcode: guestcode,
        gscode: gscode,
        id: val
      }).then(res => {
        this.newsform.id = res.data.id;
        this.newsform.title = res.data.title;
        this.newsform.newstitle = res.data.title;
        this.newsform.content = res.data.body;
      });
    },
    refresh() {
      this.reload();
    },
    imgHandler(state) {
      let quill = this.$refs.quillEditor.quill;
      this.addRange = quill.getSelection();
      if (state) {
        let fileInput = document.getElementById("imgInput");
        fileInput.click(); // 加一个触发事件
      }
      this.uploadType = "image";
    },
    submit() {},
    beforeUpload(file) {
      this.uploadData.guestcode = JSON.parse(
        JSON.stringify(this.$store.state.user.user.info)
      ).reguserno;
      this.uploadData.gscode = JSON.parse(
        JSON.stringify(this.$store.state.user.user.info)
      ).gscode;
    },
    upScuccess(e) {
      let path = e.statusText;
      let url = "http://img.inheart.cn" + path;
      let quill = this.$refs.quillEditor.quill;
      let selection = quill.getSelection();

      // 获取光标的位置
      let cursorIndex = selection ? selection.index : 0;
      // 插入图片到编辑器
      quill.insertEmbed(cursorIndex, "image", url);
      // 调整光标到最后
      quill.setSelection(cursorIndex + 1);
    },
    onEditorBlur(quill) {}, // 失去焦点事件
    onEditorFocus(quill) {}, // 获得焦点事件
    onEditorReady(quill) {}, // 内容改变事件
    handleRemove(file, fileList) {
      // console.log(file, fileList);
    },
    // 转码
    escapeStringHTML(str) {
      str = str.replace(/&lt;/g, "<");
      str = str.replace(/&gt;/g, ">");
      return str;
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    getediter() {
      let quill = this.$refs.quillEditor.quill;
      // 监听工具栏图片点击
      quill.getModule("toolbar").addHandler("image", this.imgHandler);
    },
    clearediter() {
      this.resetForm("newsform");
      this.newsform.content = "";
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  computed: {
    editor() {
      return this.$refs.quillEditor.quill;
    }
  }
};
</script>

<style lang="scss" scoped>
.page-content {
  height: 100%;
  background: #fff;
  padding: 20px;

  .head {
    overflow: hidden;
    transition: height 0.3s;
  }
  .el-col {
    width: 50%;
  }
  .article-list {
    .item {
      padding: 18px 0;
      display: flex;
      justify-content: space-between;
      border-bottom: 1px solid #eee;
      position: relative;

      &:last-of-type {
        border: 0;
      }

      .left {
        max-width: 43%;

        .title {
          color: #333333;
          font-size: 18px;
          font-weight: 500;
          display: inline-block;
          display: -webkit-box;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;

          &:hover {
            color: $theme-color;
            cursor: pointer;
          }
        }

        .des {
          color: #515a6e;
          font-size: 14px;
          line-height: 22px;
          margin: 10px 0 30px 0;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 3;
          overflow: hidden;
        }

        .date {
          margin-top: 10px;
          color: #515a6e;
          font-size: 13px;
        }

        .outer {
          display: flex;
          position: absolute;
          left: 0;
          bottom: 18px;
          line-height: 32px;
          > div {
            margin-right: 15px;
            padding-right: 15px;
            border-right: 1px solid #ddd;

            i {
              color: #515a6e;
              font-size: 16px;
              position: relative;
              top: 1px;
            }

            span {
              color: #515a6e;
              font-size: 14px;
              margin-left: 3px;
            }

            &:last-of-type {
              border: 0;
            }
          }
        }
      }

      .right {
        .cover {
          width: 200px;
          // height: 120px;
          border-radius: 3px;

          img {
            width: 100%;
            height: 100%;
            border-radius: 3px;
          }
        }
      }
    }
  }
  .editor {
    margin-top: 15px;

    .ql-editor {
      min-height: 500px;
    }
  }
}

@media only screen and (max-width: $device-ipad) {
  .page-content {
    padding: 20px;
    .el-col {
      width: 100%;
    }
    .head .el-input {
      width: 74% !important;
      max-width: 125px !important;
    }
    .article-list {
      .item {
        padding: 18px 0;
        display: block;

        &:first-of-type {
          padding-top: 0;
        }

        .left {
          max-width: 100%;

          .des {
            margin: 5px 0 10px 0;
            @include ellipsis(2);
          }

          .outer {
            position: absolute;
            bottom: 12px;
          }
        }

        .right {
          padding-bottom: 20px;

          .cover {
            width: 100%;
            height: 300px;
            padding-bottom: 40%;
            position: relative;

            img {
              width: 100%;
              height: 100%;
              position: absolute;
            }
          }
        }
      }
    }
  }
}
</style>
